package com.example.administrator.liveapp.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.support.v4.content.res.ResourcesCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.example.administrator.liveapp.ApplicationUtils;
import com.example.administrator.liveapp.R;
import com.example.administrator.liveapp.Xutils3.MyCallBack;
import com.example.administrator.liveapp.Xutils3.XUtils;
import com.example.administrator.liveapp.bean.ShoppingCartBean;
import com.example.administrator.liveapp.utils.AppUrl;
import com.example.administrator.liveapp.utils.NumberAddSubView;
import com.example.administrator.liveapp.view.FullyLinearLayoutManager;
import com.google.gson.Gson;
import com.makeramen.roundedimageview.RoundedImageView;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.HashMap;
import java.util.Map;

/**
 * 商城购物车activity
 */

public class ShoppingCart extends AppCompatActivity implements View.OnClickListener {

    private RecyclerView shopping_book_recycle;
    private ShoppingCartBean bean;
    private CheckBox ck_all;
    private TextView tv_show_price;
    private TextView tv_settlement;
    private TextView bianji;
    private ShoppingCartBook book;
    private TextView no_content;
    private RelativeLayout rl_bottom;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ApplicationUtils applicationUtils = new ApplicationUtils();
        applicationUtils.addActivity(this);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("action.refreshFriend");
        registerReceiver(mRefreshBroadcastReceiver, intentFilter);
        initView();
        initData();
    }

    private BroadcastReceiver mRefreshBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("action.refreshFriend"))
            {
                initData();
                for (int i = bean.getCart().size() - 1; i >= 0; i--) {
                    if (bean.getCart().get(i).isSelect()) {
                        bean.getCart().remove(i);
                    }
                }
                book.notifyDataSetChanged();
            }
        }
    };

    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mRefreshBroadcastReceiver);
    }

    private void initView() {
        setContentView(R.layout.activity_shopping_cart);
        shopping_book_recycle = (RecyclerView) findViewById(R.id.shopping_book_recycle);
        ck_all = (CheckBox) findViewById(R.id.ck_all);
        tv_show_price = (TextView) findViewById(R.id.tv_show_price);
        tv_settlement = (TextView) findViewById(R.id.tv_settlement);
        no_content = (TextView) findViewById(R.id.no_content);
        rl_bottom = (RelativeLayout) findViewById(R.id.rl_bottom);
        bianji = (TextView) findViewById(R.id.bianji);
        findViewById(R.id.shopping_returns).setOnClickListener(this);
        tv_settlement.setOnClickListener(this);
        bianji.setOnClickListener(this);
        ck_all.setOnClickListener(this);
    }


    private void initData() {
        String url = AppUrl.URL + AppUrl.shopCartURL;
        Map<String, String> map = new HashMap<>();
        map.put("cartUid", ApplicationUtils.getInstance().loginBean.getConsumerid());
        XUtils.Get(url, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                bean = gson.fromJson(result, ShoppingCartBean.class);
                if (bean.isResult()) {
                    //图书
                    FullyLinearLayoutManager line2 = new FullyLinearLayoutManager(ShoppingCart.this);
                    shopping_book_recycle.setLayoutManager(line2);
                    shopping_book_recycle.setHasFixedSize(true);
                    book = new ShoppingCartBook();
                    shopping_book_recycle.setAdapter(book);

                } else if (bean.getCode() == 6405) {
                    no_content.setText("亲,你购物车是空的!");
                    no_content.setVisibility(View.VISIBLE);
                    rl_bottom.setVisibility(View.GONE);
                } else {
                    Toast.makeText(ShoppingCart.this, bean.getMessage() + "数据加载失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }
        });
    }

    java.text.DecimalFormat df = new java.text.DecimalFormat("0.00");//精确到小数点后两位
    public double money = 0;
    public double sun = 0;
    double freights = 0;
    String id;

    class ShoppingCartBook extends RecyclerView.Adapter<ShoppingCartBook.ViewHolder> {
        public Context context;

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.shopping_cart_item, null);
            ViewHolder viewHolder = new ViewHolder(view);
            context = parent.getContext();
            return viewHolder;
        }

        @Override
        public void onBindViewHolder(final ShoppingCartBook.ViewHolder holder, final int position) {

            Glide.with(context).load(AppUrl.URL + bean.getCart().get(position).getBookimgurl()).into(holder.shopping_book_image);
            holder.shopping_book_name.setText(bean.getCart().get(position).getBooktitle());
            holder.shopping_book_number.setValue(Integer.parseInt(bean.getCart().get(position).getCartcount()));
            holder.shopping_book_money.setText("¥" + bean.getCart().get(position).getBookprice());
            holder.shopping_book_number2.setText("×" + bean.getCart().get(position).getCartcount());
            holder.ck_chose.setChecked(bean.getCart().get(position).isSelect());
            if (bianji.getText().equals("编辑")) {
                holder.shopping_book_number.setVisibility(View.GONE);
                holder.shopping_book_number2.setVisibility(View.VISIBLE);
            } else if (bianji.getText().equals("完成")) {
                holder.shopping_book_number.setVisibility(View.VISIBLE);
                holder.shopping_book_number2.setVisibility(View.GONE);
            }
            //bean.getCart().get(position).setNum(holder.shopping_book_number.getValue());
            holder.shopping_book_number.setOnNumberClickListener(new NumberAddSubView.OnNumberClickListener() {
                @Override
                public void subNumber(View view, int Value) {
                    bean.getCart().get(position).setNum(Value);
                    bean.getCart().get(position).setCartcount(""+Value);
                }

                @Override
                public void addNumber(View view, int Value) {
                    bean.getCart().get(position).setNum(Value);
                    bean.getCart().get(position).setCartcount(""+Value);
                }
            });
            sun = 0;
            holder.ck_chose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    bean.getCart().get(position).setSelect(!bean.getCart().get(position).isSelect());
                    int count = 0;
                    for (int i = 0; i < bean.getCart().size(); i++) {
                        if (bean.getCart().get(i).isSelect()) {
                            money = Integer.parseInt(bean.getCart().get(i).getCartcount()) * (Double.parseDouble(bean.getCart().get(i).getBookprice())*Double.parseDouble(bean.getCart().get(i).getDiscount()));
                            sun = sun + money;
                            count++;
                        }

                    }
                    /**
                     * 计算邮费
                     */
                    freights=0;
                    for (int j = 0; j < bean.getFreight().size(); j++) {
                        double number = 0.00;
                        for (int i = 0; i < bean.getCart().size(); i++) {
                            if (bean.getCart().get(i).isSelect()) {
                                if (bean.getCart().get(i).getStorename().equals(bean.getFreight().get(j).getStorename())) {
                                    if (number < Double.parseDouble(bean.getCart().get(i).getFreight())) {
                                        number = Double.parseDouble(bean.getCart().get(i).getFreight());
                                    }

                                }
                            }


                        }
                        freights += number;
                    }
                    ck_all.setChecked(count == bean.getCart().size());
                    tv_show_price.setText("合计¥ :" + df.format(sun+freights) + "元(含邮费:" + df.format(freights) + ")");
                    book.notifyDataSetChanged();
                }
            });

        }


        @Override
        public int getItemCount() {
            return bean.getCart().size();
        }

        public class ViewHolder extends RecyclerView.ViewHolder {
            public CheckBox ck_chose;
            public RoundedImageView shopping_book_image;
            public TextView shopping_book_name;
            public TextView shopping_book_money;
            public NumberAddSubView shopping_book_number;
            public TextView shopping_book_number2;

            public ViewHolder(View itemView) {
                super(itemView);
                ck_chose = (CheckBox) itemView.findViewById(R.id.ck_chose);
                shopping_book_image = (RoundedImageView) itemView.findViewById(R.id.shopping_book_image);
                shopping_book_name = (TextView) itemView.findViewById(R.id.shopping_book_name);
                shopping_book_money = (TextView) itemView.findViewById(R.id.shopping_book_money);
                shopping_book_number = (NumberAddSubView) itemView.findViewById(R.id.shopping_book_number);
                shopping_book_number2 = (TextView) itemView.findViewById(R.id.shopping_book_number2);
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.shopping_returns:
                finish();
                break;
            case R.id.ck_all:
                if (bean != null) {
                    int count = 0;
                    sun = 0;
                    for (int i = 0; i < bean.getCart().size(); i++) {
                        if (bean.getCart().get(i).isSelect()) {
                            count++;
                        }
                    }
                    for (int i = 0; i < bean.getCart().size(); i++) {
                        bean.getCart().get(i).setSelect(count != bean.getCart().size());
                        if (count != bean.getCart().size()) {
                            money = Integer.parseInt(bean.getCart().get(i).getCartcount()) * (Double.parseDouble(bean.getCart().get(i).getBookprice())*Double.parseDouble(bean.getCart().get(i).getDiscount()));
                            sun = sun + money;
                        }
                    }
                    /**
                     * 计算邮费
                     */
                    freights=0;
                    for (int j = 0; j < bean.getFreight().size(); j++) {
                        double number = 0;
                        for (int i = 0; i < bean.getCart().size(); i++) {
                            if (count != bean.getCart().size()) {
                                if (bean.getCart().get(i).getStorename().equals(bean.getFreight().get(j).getStorename())) {
                                    if (number < Double.parseDouble(bean.getCart().get(i).getFreight())) {
                                        number = Double.parseDouble(bean.getCart().get(i).getFreight());
                                    }
                                }
                            }
                        }
                        freights += number;
                    }

                    tv_show_price.setText("合计¥ :" + df.format(sun+freights) + "元(含邮费:" + df.format(freights) + ")");
                    book.notifyDataSetChanged();
                }
                break;
            case R.id.bianji:
                if (bianji.getText().equals("编辑")) {
                    tv_show_price.setVisibility(View.GONE);
                    tv_settlement.setText("删除");
                    bianji.setText("完成");
                } else if (bianji.getText().equals("完成")) {
                    ck_all.setChecked(false);
                    tv_show_price.setText("合计:0.00元");
                    tv_show_price.setVisibility(View.VISIBLE);
                    tv_settlement.setText("结算");
                    bianji.setText("编辑");
                    String url = AppUrl.URL + AppUrl.EditCartURL;
                    String ids2 = "";
                    String number = "";
                    String numbers = "";
                    for (int i = 0; i < bean.getCart().size(); i++) {
                        id = bean.getCart().get(i).getBookid();
                        ids2 += id + "-";
                        number = bean.getCart().get(i).getCartcount() + "";
                        numbers += number + "-";
                    }
                    Map<String, String> map2 = new HashMap<>();
                    map2.put("consumerId", ApplicationUtils.getInstance().loginBean.getConsumerid());
                    map2.put("bookId", ids2);
                    map2.put("count", numbers);
                    XUtils.Get(url, map2, new MyCallBack<String>() {
                        @Override
                        public void onSuccess(String result) {
                            super.onSuccess(result);
                        }

                        @Override
                        public void onError(Throwable ex, boolean isOnCallback) {
                            super.onError(ex, isOnCallback);
                            Toast.makeText(ShoppingCart.this, ex.getMessage() + "", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onFinished() {
                            super.onFinished();
                            initData();
                        }
                    });
                }
                if(book!=null){
                    if (book.getItemCount() == 0) {
                        return;
                    }
                    book.notifyDataSetChanged();
                }
                break;
            case R.id.tv_settlement:
                if (tv_settlement.getText().equals("删除")) {
                    String ids = "";
                    String url = AppUrl.URL + AppUrl.EditCartURL;
                    for (int i = 0; i < bean.getCart().size(); i++) {
                        if (bean.getCart().get(i).isSelect()) {
                            id = bean.getCart().get(i).getBookid();
                            ids += id + "-";
                        }
                    }
                    if (ids.equals("")) {
                        Toast.makeText(this, "请选择删除的商品", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    Map<String, String> map = new HashMap<>();
                    map.put("consumerId", ApplicationUtils.getInstance().loginBean.getConsumerid());
                    map.put("bookId", ids);
                    map.put("deleteStatus", "1");
                    XUtils.Get(url, map, new MyCallBack<String>() {
                        @Override
                        public void onSuccess(String result) {
                            super.onSuccess(result);
                            Toast.makeText(ShoppingCart.this, "商品删除成功", Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onError(Throwable ex, boolean isOnCallback) {
                            super.onError(ex, isOnCallback);
                        }

                        @Override
                        public void onFinished() {
                            super.onFinished();
                            for (int i = bean.getCart().size() - 1; i >= 0; i--) {
                                if (bean.getCart().get(i).isSelect()) {
                                    bean.getCart().remove(i);
                                }
                            }
                            book.notifyDataSetChanged();
                        }
                    });
                } else if (tv_settlement.getText().equals("结算")) {
                    int a = 0;
                    if(bean!=null&&!bean.equals("")){
                        for (int i = 0; i <bean.getCart().size() ; i++) {
                            if(bean.getCart().get(i).isSelect()){
                                a++;
                            }
                        }
                        if(a!=0){
                            String bookid = "";
                            String bookids = "";
                            String num = "";
                            String bookNums="";
                            for (int i = 0; i < bean.getCart().size(); i++) {
                                if (bean.getCart().get(i).isSelect()) {
                                    bookid = bean.getCart().get(i).getBookid();
                                    num = bean.getCart().get(i).getCartcount()+"";
                                    bookids+=bookid+"-";
                                    bookNums+=num+"-";
                                }
                            }
                            /**
                             * 计算总价格
                             */
                            sun = 0;
                            for (int i = 0; i < bean.getCart().size(); i++) {
                                if (bean.getCart().get(i).isSelect()) {
                                    money = Integer.parseInt(bean.getCart().get(i).getCartcount()) * (Double.parseDouble(bean.getCart().get(i).getBookprice())*Double.parseDouble(bean.getCart().get(i).getDiscount()));
                                    sun = sun + money;
                                }

                            }
                            /**
                             * 计算邮费
                             */
                            freights=0;
                            for (int j = 0; j < bean.getFreight().size(); j++) {
                                double number = 0.00;
                                for (int i = 0; i < bean.getCart().size(); i++) {
                                    if (bean.getCart().get(i).isSelect()) {
                                        if (bean.getCart().get(i).getStorename().equals(bean.getFreight().get(j).getStorename())) {
                                            if (number < Double.parseDouble(bean.getCart().get(i).getFreight())) {
                                                number = Double.parseDouble(bean.getCart().get(i).getFreight());
                                            }

                                        }
                                    }


                                }
                                freights += number;
                            }
                            Intent intent = new Intent(ShoppingCart.this,CommodityPayActivity.class);
                            intent.putExtra("sum",df.format(sun+freights));
                            intent.putExtra("freights",df.format(freights));
                            intent.putExtra("bookId",bookids);
                            intent.putExtra("bookNum",bookNums);
                            intent.putExtra("status","1");
                            startActivity(intent);
                            overridePendingTransition(R.anim.zoomin,R.anim.zoomout);
                        }else{
                            Toast.makeText(this, "请至少选择一种商品支付", Toast.LENGTH_SHORT).show();
                        }
                    }else{
                        Toast.makeText(this, "请至少选择一种商品支付", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
        }
    }

}
